{% extends "layout.html" %}
{% block body %}
<!-- Unknown Words -->
<div x-show="!$.isEmptyObject(unknownWords)" x-cloak>
    <h5 class="text-danger">Unknown Words</h5>
    <div class="form-group">
        <div class="form-row pl-1">
            <p>
                Rhasspy guessed how the words below are pronounced, but you should <a href="#" onclick="showPhonemes()">check to be sure.</a>
            </p>
            <p>
                If everything looks good, click <strong>Confirm Guesses</strong> below.</p>
        </div>
    </div>
    <div class="form-group">
        <div class="form-row">
            <textarea id="unknownWords" class="form-control" style="border-width: 3px; border-color: red;" type="text" rows="5" x-model="unknownWordsText.value"></textarea>
        </div>
    </div>
    <div class="form-group">
        <div class="form-row">
            <button class="btn btn-danger" onclick="confirmGuesses()" title="Confirm that Rhasspy's pronunciation guesses are correct">Confirm Guesses</button>
        </div>
    </div>

    <hr>

    <h5>Custom Words</h5>
</div>
<!-- End Unknown Words -->

<!-- Custom Words -->
<div x-data="{ ...rhasspy, 'words': words }">
    <div class="form-group">
        <div class="form-row text-muted pl-1">
            <p>
                These are words whose pronunciations you want to customize.
                Each line contains a word followed <a href="#" onclick="showPhonemes()">its phonetic pronunciation</a> (separated by spaces):
                <br>
                <tt>test T EH S T</tt>
            </p>
        </div>
    </div>
    <div class="form-group">
        <div class="form-row">
            <div class="col">
                <button onclick="saveWords()" x-bind:class="{ 'btn-danger': words.isDirty.value }" class="btn btn-primary">Save Custom Words</button>
            </div>
        </div>
    </div>
    <div class="form-group">
        <div class="form-row">
            <div class="col-xs-auto">
                <button type="button" class="btn btn-success" onclick="guessWord()">Guess Word</button>
            </div>
            <div class="col-xs-auto">
                <button id="addWord" type="button" class="btn btn-warning" onclick="addGuessedWord()" style="display: none;">Add</button>
            </div>
            <div class="col-xs-auto">
                <input id="word" type="text" class="form-control" placeholder="word">
            </div>
            <span id="inDictionary" title="Word is in a dictionary" style="display:none">
                <i class="fas fa-book"></i>
            </span>
        </div>
    </div>
    <div id="guess-group" class="form-group" style="display: none;">
        <div class="form-row">
            <div class="col">
                <select id="guesses" class="form-control" onchange="updatePhonemes()">
                    <option disabled value="">Select Guess</option>
                </select>
            </div>
        </div>
    </div>
    <div id="guess-group" class="form-group">
        <div class="form-row">
            <div class="col-xs-auto">
                <button id="pronounce" type="button" class="btn btn-info" onclick="pronouncePhonemes()">Pronounce</button>
            </div>
            <div class="col">
                <input id="phonemes" type="text" class="form-control" placeholder="phonemes">
            </div>
        </div>
    </div>
    <div class="form-group">
        <div class="form-row">
            <textarea x-model="words.customWords.value" x-bind:class="{ 'border-danger': words.isDirty.value }" class="form-control" style="border-width: 3px" type="text" rows="25" oninput="words.isDirty.value = true"></textarea>
        </div>
    </div>
    <div class="form-group">
        <div class="form-row">
            <button onclick="saveWords()" x-bind:class="{ 'btn-danger': words.isDirty.value }" class="btn btn-primary">Save Custom Words</button>
        </div>
    </div>

    <!-- Phoneme Table -->
    <div id="phonemesModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="phonemesModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 id="phonemesModalLabel" class="modal-title">Available Phonemes (<span x-text="profile.speech_to_text.system"></span>)</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <table class="table">
                        <thead class="thead-light">
                            <th scope="col">Phoneme</th>
                            <th scope="col">Example</th>
                            <th scope="col">Translation</th>
                            <th scope="col"></th>
                        </thead>
                        <tbody>
                            <template x-for="p in Object.keys(words.phonemes.value)" :key="p">
                                <tr>
                                    <td x-text="p">{{ phoneme }}</td>
                                    <td x-text="words.phonemes.value[p].word"></td>
                                    <td x-text="words.phonemes.value[p].phonemes"></td>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

</div>
<!-- End Custom Words -->

{% endblock %}

{% block script %}
<script type="text/javascript">
 var words = {
     isDirty: { value: false },
     customWords: { value: '' },
     phonemes: { value: {} }
 }

 // Displays dialog with phoneme table
 function showPhonemes() {
     $.get('{{ url_prefix }}/api/phonemes', (r) => {
         console.log(r)
         words.phonemes.value = r;
         $('#phonemesModal').modal('show');
     })
 }

 // Formats unknown words as a CMU pronunciation dictionary
 function formatUnknownWords() {
     return Object.entries(rhasspy.unknownWords)
                  .map((kv) => kv[0] + ' ' + kv[1])
                  .join('\n');
 }

 // Calls /api/lookup and shows word pronunciation(s)
 function guessWord() {
     $('#guesses option').remove();
     $('#guess-group').hide();
     $('#addWord').hide();
     $('#inDictionary').hide();

     let word = $('#word').val() || '';
     if (word.length > 0) {
         rhasspy.postBusy('Guessing word', '/api/lookup', word)
                .done(function(response) {
                    if (response.in_dictionary) {
                        $('#inDictionary').show();
                    } else {
                        $('#addWord').show();
                    }

                    response.pronunciations.forEach(function(phonemes) {
                        $('#guesses').append('<option>' + phonemes + '</option>');
                    })

                    $('#guess-group').show();
                    updatePhonemes();
                });
     } else {
         alert('Please enter a word to guess')
     }
 }

 // Copies the selected word/pronunciation into custom words text box
 function addGuessedWord() {
     var word = $('#word').val() || '';
     var guessPhonemes = $('#guesses').val() || '';
     if ((word.length > 0) && (guessPhonemes.length > 0)) {
         if ((words.customWords.value.length > 0) && !words.customWords.value.endsWith('\n')) {
             words.customWords.value += '\n';
         }

         words.customWords.value += word + ' ' + guessPhonemes;
         words.isDirty.value = true;
     } else {
         alert('No word or pronunciation')
     }
 }

 // Saves custom words and re-trains
 function saveWords() {
     rhasspy.postBusy('Saving custom words',
                      '/api/custom-words',
                      words.customWords.value,
                      false)
            .done(function() {
                words.isDirty.value = false;

                if (window.confirm("Words saved. Retrain Rhasspy?")) {
                    rhasspy.train();
                } else {
                    rhasspy.hideBusy();
                }
            });
 }

 // Copies all guessed pronunciations to custom words and saves
 function confirmGuesses() {
     if ((words.customWords.value.length > 0) && !words.customWords.value.endsWith('\n')) {
         words.customWords.value += '\n';
     }

     words.customWords.value += rhasspy.unknownWordsText.value

     rhasspy.unknownWordsText.value = '';
     saveWords();
 }

 // POST to /api/pronounce to speak phonetic word pronunciation
 function pronouncePhonemes() {
     var phonemes = $('#phonemes').val()
     $('#pronounce').prop('disabled', true);
     rhasspy.postBusy('Pronouncing word', '/api/pronounce', phonemes)
            .always(function() {
                $('#pronounce').prop('disabled', false);
            });
 }

 function updatePhonemes() {
     // Copy guess into phonemes text box
     $('#phonemes').val($('#guesses').val());
 }

 // Warns users that custom words are not saved
 window.onbeforeunload = function() {
     if (words.isDirty.value) {
         return 'Custom words were not saved. Are you sure?"'
     }
 }

 $(document).ready(() => {
     // Load custom words
     $.get('{{ url_prefix }}/api/custom-words', (r) => words.customWords.value = r);

     // Catch ENTER and guess word pronuncation(s)
     $("#word").keypress(function() {
         if (event.which == 13) {
             event.preventDefault();
             guessWord();
         }
     })
 })
</script>
{% endblock %}
